package cn.source.system.controller.api;

import cn.source.common.constant.Constants;
import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.entity.SysUser;
import cn.source.common.core.domain.model.*;
import cn.source.common.core.page.TableDataInfo;
import cn.source.common.core.redis.RedisCache;
import cn.source.common.utils.SecurityUtils;
import cn.source.common.utils.StringUtils;
import cn.source.framework.web.service.TokenH5Service;
import cn.source.system.asp.NoNeedCheck;
import cn.source.system.asp.UserH5ContextHandler;
import cn.source.system.domain.AaUser;
import cn.source.system.service.IAaDataService;
import cn.source.system.service.IAaUserService;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 三方登录验证
 *
 * @author ruoyi
 */
@RequestMapping("/api/sp")
@RestController
public class ApiLoginController extends BaseController
{

    @Autowired
    private IAaUserService aaUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenH5Service tokenH5Service;

    @Autowired
    private IAaDataService aaDataService;


    /**
     * 三方登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/thirdLogin")
    @NoNeedCheck
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String msg = "登录成功";
        if (StringUtils.isEmpty(loginBody.getUsername())){
            msg = "用户名不能为空";
            return error(msg);
        }
        if (StringUtils.isEmpty(loginBody.getPassword())){
            msg = "密码不能为空";
            return error(msg);
        }
        AaUser aaUser = aaUserService.queryByUserName(loginBody.getUsername());
        if (aaUser == null){
            msg = "登录账号不存在";
            return error(msg);
        }
        if(aaUser.getUserStatus() != 0){
            msg = "账号已经冻结";
            return error(msg);
        }
        if(!aaUser.getUserPassWord().equals(loginBody.getPassword())){
            msg = "密码错误";
            return error(msg);
        }
        //修改登录时间
        aaUser.setLoginDate(new Date());
        aaUserService.updateAaUser(aaUser);
        H5User h5User = new H5User();
        BeanUtils.copyProperties(aaUser , h5User);
        //设置token
        H5LoginUser loginUser = new H5LoginUser(h5User,null);
        loginUser.setUserId(aaUser.getId());
        String token = tokenH5Service.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        ajax.put("loginUser", loginUser);
        return ajax;
    }


    /**
     * 手机注册/登录
     */
    @PostMapping("/thirdRegister")
    @NoNeedCheck
    public AjaxResult thirdRegister(HttpServletRequest request,
                                    @RequestBody H5LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String msg = "注册成功";
        if (StringUtils.isEmpty(loginBody.getUsername())){
            msg = "用户名不能为空";
            return error(msg);
        }
        if (StringUtils.isEmpty(loginBody.getPassword()) || StringUtils.isEmpty(loginBody.getPasswordTwo())){
            msg = "密码不能为空";
            return error(msg);
        }
        if(!loginBody.getPassword().equals(loginBody.getPasswordTwo())){
            msg = "两次密码不一致";
            return error(msg);
        }
        Long userNum = aaUserService.countByUserName(loginBody.getUsername());
        if(userNum != null && userNum > 0){
            msg = "账号已经存在";
            return error(msg);
        }
        AaUser user = new AaUser();
        user.setUserName(loginBody.getUsername());
        user.setUserPassWord(loginBody.getPassword());
        user.setUserLevel(0);
        user.setUserIntegral(BigDecimal.ZERO);
        user.setUserStatus(0);
        user.setRegisterDate(new Date());
        aaUserService.insertAaUser(user);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        H5LoginUser loginUser = UserH5ContextHandler.get();
        AaUser user = aaUserService.selectAaUserById(loginUser.getUserId());
        if(user.getUserStatus() != 0){
            throw new AccessDeniedException("账号已经冻结");
        }
        H5User h5User = new H5User();
        BeanUtils.copyProperties(user , h5User);
        loginUser.setUser(h5User);
        tokenH5Service.refreshToken(loginUser);
        // 角色集合
        return AjaxResult.success(loginUser);
    }


    /**
     * profile 重置密码
     */
    @PutMapping("/profile/updatePwd")
    public AjaxResult updatePwd(@RequestBody JSONObject json)
    {
        H5LoginUser loginUser = UserH5ContextHandler.get();
        AaUser user = aaUserService.selectAaUserById(loginUser.getUserId());
        String oldPassword = json.getString("oldPassword");
        String newPassword = json.getString("newPassword");
        if(StringUtils.isEmpty(oldPassword)){
            AjaxResult.error("旧密码不能为空");
        }
        if(StringUtils.isEmpty(newPassword)){
            AjaxResult.error("新密码不能为空");
        }
        if(!user.getUserPassWord().equals(oldPassword)){
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if(user.getUserPassWord().equals(newPassword)){
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if(newPassword.length() < 6){
            return AjaxResult.error("密码必须大于等于6位");
        }
        user.setUserPassWord(newPassword);
        int num = aaUserService.updateAaUser(user);
        if(num > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    @GetMapping("/dataList")
    @NoNeedCheck
    public AjaxResult dataList()
    {
        return AjaxResult.success(aaDataService.selectAaDataList(null));
    }
}
